﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using PhoneAppRssReader.Entity;
using PhoneAppRssReader.Utls;

namespace PhoneAppRssReader
{
    public partial class EditRssPage : PhoneApplicationPage
    {
        public EditRssPage()
        {
            InitializeComponent();
            TitleTextBox.Focus();
        }

        private int _index = -1;
        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            var queryString = NavigationContext.QueryString["index"];
            if (string.IsNullOrEmpty(queryString)) return;
            var index = Convert.ToInt32(queryString);

            var feed = App.Source.Items[index];

            TitleTextBox.Text = feed.Title;
            LinkTextBox.Text = feed.Url;
            _index = index;

        }


        private void Home(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
        }

        private void EditRss(object sender, EventArgs e)
        {
            if (_index == -1) return;

            var editFeed = App.Source.Items[_index];
            var updateFeed = new Feed { Id = editFeed.Id, Title = TitleTextBox.Text, Url = LinkTextBox.Text };
            var success = XmlAction.EditFeed(updateFeed);
            if (success)
            {
                MessageBox.Show("Write success");
                editFeed.Title = updateFeed.Title;
                editFeed.Url = updateFeed.Url;
                NavigationService.Navigate(new Uri("/ManagerRssFeedPage.xaml", UriKind.Relative));
            }
            else
            {
                MessageBox.Show("Failure");
            }
        }

        private void Reset(object sender, EventArgs e)
        {
            var editFeed = App.Source.Items.ElementAt(_index);
            TitleTextBox.Text = editFeed.Title;
            LinkTextBox.Text = editFeed.Url;
            TitleTextBox.Focus();
        }
        private void ManagerRssFeed(object sender, EventArgs e)
        {
            // TODO: Add event handler implementation here.
            NavigationService.Navigate(new Uri("/ManagerRssFeedPage.xaml", UriKind.Relative));
        }

    }
}